package com.jackrain.nea.fc.dl.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.*;
import com.jackrain.nea.dl.common.utils.esutil.ConvertQueryListUtil;
import com.jackrain.nea.dl.common.utils.esutil.ElasticsearchUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.WmsTranInSaveCmd;
import com.jackrain.nea.fc.dl.mapper.WmsTranMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.RuntimeCompute;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

/**
 * 调拨入库单->FC
 *
 * @author xuxinshuai
 * @date 2018/05/05
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class WmsTranInSaveCmdImpl extends CommandAdapter implements WmsTranInSaveCmd {


    @Autowired
    PostDubbleEvent postDubbleEvent;
    @Autowired
    PostHandleEvent postHandleEvent;

    @Autowired
    QueryCpUtil postQueryEvemt;
    @Autowired
    QueryUserUtil postUserEvent;

    @Autowired
    private ElasticsearchUtil esUtil;

    @Autowired
    private ConvertQueryListUtil convertQLUtil;

    @Autowired
    private BtranEsName btranEsName;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        WmsTranMapper wmsTranMapper = ApplicationContextHandle.getBean(WmsTranMapper.class);
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！");
        }
        log.info("WmsTranInSaveCmdImpl-param--->{}", param);

        RuntimeCompute runtimeCompute = ApplicationContextHandle.getBean("runtimeCompute");
        runtimeCompute.startRuntime();

        JSONArray dataArray = param.getJSONArray("data");

        JSONArray succesIdArray = new JSONArray();
        JSONArray queryDataArray = new JSONArray();
        JSONArray errArray = new JSONArray();

        for (int i = 0; i < dataArray.size(); i++) {


            JSONObject dataJo = dataArray.getJSONObject(i);
            JSONObject oldJo = dataJo.getJSONObject("DL_B_TRNN_IN");
            String billnoid = oldJo.getString("ID");
            String store_date_in = dateToStrLong(oldJo.getDate("DATE_IN"));
            String WMS_BILL_NO = oldJo.getString("WMS_BILL_NO");
            String bill_no = oldJo.getString("BILL_NO");

            try {
                Long objid = wmsTranMapper.selectTraninBillnoId(bill_no);
                if (objid == null) {
                    throw new NDSException(oldJo.getString("BILL_NO") + "查不到对应的单据ID！");
                }
                JSONArray itemDataArray = dataJo.getJSONArray("DL_B_TRAN_IN_V_ITEM_SKU");
                JSONArray itemArray = new JSONArray();

                for (int a = 0; a < itemDataArray.size(); a++) {

                    JSONObject itemoldJo = itemDataArray.getJSONObject(a);
                    JSONObject newItemJo = new JSONObject();
                    String skuecode = itemoldJo.getString("SKU");
                    Long tranid = wmsTranMapper.selectTranId(objid, skuecode);
                    if (null == tranid) {
                        newItemJo.put("ID", -1);
                    } else {
                        newItemJo.put("ID", tranid);
                    }
                    newItemJo.put("QTY_IN", itemoldJo.getString("QTY_IN"));
                    //取条码ID
                    JSONObject whereJo5 = new JSONObject();
                    whereJo5.put("ECODE", skuecode);
                    whereJo5.put("CP_C_DISTRIB_ID", "0");
                    JSONObject cpmap5 = postQueryEvemt.queryCP("PS_C_SKU", "ID", whereJo5);
                    if (cpmap5 == null) {
                        throw new NDSException(skuecode + "找不到对应的条码ID！");
                    }
                    Long skuId = TypeUtils.castToLong(cpmap5.getLong("ID"));
                    newItemJo.put("PS_C_SKU_ID", skuId);
                    newItemJo.put("PS_C_SKU_ECODE", skuecode);

                    itemArray.add(newItemJo);
                }

                User user = postUserEvent.getUser(UserInformation.USER_NAME);

                //1.调用保存服务
                QuerySessionImpl tranquerySession = new QuerySessionImpl(user);
                DefaultWebEvent tranevent = new DefaultWebEvent("dltranIn", new HashMap(16));
                JSONObject tranJo = new JSONObject();

                tranJo.put("objid", objid);
                tranJo.put("isWMSCheck", "N");
                tranJo.put("STORE_DATE_IN", store_date_in);

                JSONObject tranIn = new JSONObject();
                JSONObject fixColumJo = new JSONObject();
                tranIn.put("STORE_DATE_IN", store_date_in);
                tranIn.put("varchar1", WMS_BILL_NO);

                fixColumJo.put("DL_B_TRAN_IN", tranIn);
                fixColumJo.put("DL_B_TRAN_IN_V_ITEM_SKU", itemArray);
                tranJo.put("fixcolumn", fixColumJo);
                tranJo.put("table", "DL_B_TRAN_IN");
                tranevent.put("param", tranJo);
                log.info("resultJson==>" + tranJo.toString());

                tranquerySession.setEvent(tranevent);
                JSONObject tranretJo = postHandleEvent.executePostHandle(tranJo, tranquerySession, tranevent, "save");
                log.debug("保存返回结果>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + tranretJo);

                if (tranretJo.get("code") != null && (int) tranretJo.get("code") < 0) {
                    throw new NDSException("DL_B_TRAN_IN保存失败:" + tranretJo.get("message") + tranretJo.get("error") + tranretJo.get("data"));
                }
                queryDataArray.add(tranJo);

                //2.调用验收服务
                tranevent.setParameter("command", "com.jackrain.nea.dl.tran.api.BtraninCheckInCmd:1.0:dl");
                tranevent.setParameter("table", "DL_B_TRAN_IN");
                tranevent.setParameter("webaction", "DL_B_TRAN_IN_CHECK_S_BEFOR");
                tranquerySession.setEvent(tranevent);

                JSONObject accJo = postHandleEvent.executePostHandle(tranJo, tranquerySession, tranevent, "webaction");
                log.debug("验收返回结果>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + accJo);
                if (accJo.get("code") != null && (int) accJo.get("code") < 0) {
                    throw new NDSException("验收失败:" + accJo.get("message") + accJo.get("error") + accJo.get("data"));
                }
                succesIdArray.add(billnoid);

            } catch (Exception e) {

                JSONObject errrobj = new JSONObject();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                if (e instanceof NDSException) {
                    errrobj.put("message", e.getMessage());
                } else {
                    errrobj.put("message", sw.toString());
                }
                errrobj.put("key", billnoid);
                errArray.add(errrobj);
            }

        }

        if (errArray.size() > 0) {
            vh.put("error", errArray);
            vh.put("successIds", succesIdArray);
            vh.put("code", -1);
        } else {
            vh.put("successIds", succesIdArray);
            vh.put("code", 0);
        }
        vh.put("queryDataArray", queryDataArray);
        Double spendTime = runtimeCompute.endRuntime();
        vh.put("spendtime", spendTime);
//        log.debug("---------返回结果--------->>" + vh);

//        log.debug("---------入库回传（调拨入库回传）执行时间--------->>" + spendTime);

        return vh;

    }

    /**
     * list TO jsonarra
     *
     * @param mapList
     * @return jsonArray
     */
    public JSONArray listToJsonarray(List<HashMap> mapList) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < mapList.size(); i++) {
            HashMap map = (HashMap) mapList.get(i);
            JSONObject jsonObject = new JSONObject(map);
            JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
            jsonArray.add(param);
        }
        return jsonArray;
    }

    /**
     * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
     *
     * @param dateDate
     * @return
     */
    public static String dateToStrLong(java.util.Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

    /**
     * ES查询
     *
     * @param billNo 单据编号
     * @return id
     */
    public JSONObject es(String billNo) {
        JSONObject bill_no = esUtil.generateMatch("BILL_NO", billNo);
        List<JSONObject> terms = esUtil.packageTerm(bill_no);
        JSONObject jsonObject = null;
        try {
            jsonObject = esUtil.searchAllDataByTerms(btranEsName.getIndex(),
                    btranEsName.getIntype(), "1", "10000", terms);
            log.debug("es_jsonObject->" + jsonObject);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return jsonObject;
    }

    private JSONObject billdata(JSONObject esData) {
        JSONObject hits = esData.getJSONObject("hits");
        JSONArray hitsArray = hits.getJSONArray("hits");
        JSONObject sourceJson = hitsArray.getJSONObject(0);

        JSONObject source = sourceJson.getJSONObject("_source");

        return source;
    }


}
